/**
 * Project: Useful Programs <br>
 * Package: tools
 */
package org.leumasjaffe.util;

import java.util.Random;

import javax.swing.JOptionPane;

/**
 * Class .NumberGen in file NumberGen.java <br>
 * 
 * @author leumasjaffe
 * Created on: Aug 16, 2012
 * 
 */
public class NumberGen {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length == 0)
			args = JOptionPane.showInputDialog("Enter the commandline String").split(" ");
		
		Random rand = new Random();
		Random bool = new Random();
		boolean isBitCount = false;
		int numBits = 0, minVal = 0x7FFFFFFF, maxVal = 0x80000000, numIter = 1, type = 1;
		for (int i = 0; i < args.length; i++) {
			String arg = args[i];
			if (arg.matches("-?\\d*")) {
				int val = Integer.valueOf(arg);
				if (minVal > val)
					minVal = val;
				if (maxVal < val)
					maxVal = val;
			}
			else if (arg.charAt(0) == '-')
				switch (arg.charAt(1)) {
				case 'c': numIter = Integer.valueOf(args[++i]); break;
				case 'b': isBitCount = true; numBits = Math.min(32, Integer.valueOf(args[++i])); break;
				case 't': 
					switch (arg.charAt(2)) {
					case '2': 
					case 'b': 
					case 'B': 
						type = 0; 
						break;
					case '8':
					case 'o': 
					case 'O': 
						type = 1; 
						break;
					case '1': 
						if (arg.charAt(3) == '6') {
							type = 3; 
							break;
						}
						else if (arg.charAt(3) != '0') 
							break; 
					case 'd': 
					case 'D': 
						type = 2;
					case 'h': 
					case 'H': 
					case 'x': 
					case 'X': 
						type = 3; 
						break;
					default: break;
					} 
					break;
				default: break;
				}
			else if (arg.matches("(-h|(--)?help)"))
				usage(0);
			else
				usage(-1);
		}
		if (isBitCount) {
			boolean pmFlip = false;
			if (numBits == 32) {
				numBits--;
				pmFlip = true;
			}
			maxVal = (1 << numBits) - 1;
			while (numIter-- > 0) {
				int out = rand.nextInt(maxVal) | (pmFlip && bool.nextBoolean() ? 0x80000000 : 0x0);
				printme(out, type);
			}
		}
		else {
			maxVal -= minVal;
			while (numIter-- > 0) {
				int out = rand.nextInt(maxVal) + minVal;
				printme(out, type);
			}
		}
		System.exit(0);
	}
	
	static void printme(int out, int type) {
		String print = null;
		switch (type) {
		case 0: print = Integer.toBinaryString(out); break;
		case 1: print = Integer.toOctalString(out); break;
		case 2: print = String.valueOf(out); break;
		case 3: print = Integer.toHexString(out); break;
		default: throw new IllegalStateException();
		}
		System.out.println(print);
	}
	
	static void usage(int exit_code) {
		System.out.println("java NumberGen [-c_] [-t(2bB8oO(10)dD(16)hHxX)] -b numBits");
		System.out.println("java NumberGen [-c_] [-t(2bB8oO(10)dD(16)hHxX)] minValue maxValue");
		System.exit(exit_code);
	}

}
